package com.gin.kotlin.vegetables_kot.base

import android.graphics.drawable.Drawable
import android.widget.TextView
import androidx.annotation.IntRange
import com.bumptech.glide.request.target.CustomViewTarget
import com.bumptech.glide.request.transition.Transition

/**
 * Glide加载图像到TextView中的Target
 *
 */
class TextViewTarget(
    /**
     * 目标 TextView
     */
    private val textView: TextView,
    @IntRange(from = 0, to = 3)
    private val position: Int,
    private val width: Int? = null,
    private val height: Int? = null,
) : CustomViewTarget<TextView, Drawable>(textView) {
    /**
     * 加载失败时的操作
     * @param errorDrawable Drawable?
     */
    override fun onLoadFailed(errorDrawable: Drawable?) {
        configDrawable(errorDrawable)
    }

    /**
     * 加载成功时的操作
     * @param resource Drawable
     * @param transition Transition<in Drawable>?
     */
    override fun onResourceReady(resource: Drawable, transition: Transition<in Drawable>?) {
        configDrawable(resource)
    }

    /**
     * 清空时的操作
     * @param placeholder Drawable?
     */
    override fun onResourceCleared(placeholder: Drawable?) {
    }

    private fun configDrawable(drawable: Drawable?) {
        if (drawable == null) {
            textView.setCompoundDrawables(null, null, null, null)
        } else {
            // 设置缩放
            drawable.setBounds(0, 0, width ?: drawable.minimumWidth, height ?: drawable.minimumHeight)
            when (position) {
                0 -> textView.setCompoundDrawables(drawable, null, null, null)
                1 -> textView.setCompoundDrawables(null, drawable, null, null)
                2 -> textView.setCompoundDrawables(null, null, drawable, null)
                3 -> textView.setCompoundDrawables(null, null, null, drawable)
                else -> throw RuntimeException("非法的位置：$position")
            }

        }
    }
}